﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FortuneArterial.Core.Diagnostics
{
    public class ProcessHelper
    {
        public static string ExecuteCommand(string path, string arguments, bool useDomain = false)
        {
            string msg = string.Empty;

            Process cmd = new Process();
            //设置进程信息
            cmd.StartInfo.FileName = path;
            cmd.StartInfo.Arguments = arguments;

            if (useDomain)
            {
                //创建应用程序域
                AppDomainSetup setup = new AppDomainSetup();
                setup.ApplicationBase = System.IO.Path.GetDirectoryName(path);
                setup.PrivateBinPath = setup.ApplicationBase;
                setup.CachePath = setup.ApplicationBase;
                setup.ShadowCopyFiles = "true";
                setup.ShadowCopyDirectories = setup.ApplicationBase;
                setup.LoaderOptimization = LoaderOptimization.SingleDomain;
                setup.ApplicationName = "Run " + path;

                AppDomain app = AppDomain.CreateDomain(Path.GetFileName(path), null, setup);

                cmd.StartInfo.Domain = app.FriendlyName;
            }
            //将cmd的标准输入和输出全部重定向到.NET的程序里
            cmd.StartInfo.UseShellExecute = false; //此处必须为false否则引发异常
            cmd.StartInfo.RedirectStandardInput = true; //标准输入
            cmd.StartInfo.RedirectStandardOutput = true; //标准输出
            //不显示命令行窗口界面
            cmd.StartInfo.CreateNoWindow = true;
            cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            //启动进程
            cmd.Start();
            msg = cmd.StandardOutput.ReadToEnd();
            cmd.WaitForExit();
            cmd.Close();

            return msg;
        }
    }
}
